package com.uhb.base.util;

import com.feidee.data.report.exception.DataReporterServiceException;
import com.uhb.base.exception.RequestParamInvalidJsonException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.FieldError;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class CustomExceptionHandler implements HandlerExceptionResolver {  

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomExceptionHandler.class);

    @Override  
    public ModelAndView resolveException(HttpServletRequest request,  
            HttpServletResponse response, Object object, Exception exception) {  

        LOGGER.error(exception.getMessage(), exception);

    	ModelAndView mv = new ModelAndView();
	    MappingJackson2JsonView view = new MappingJackson2JsonView();
		mv.setView(view);
		mv.addObject("requestName", request.getRequestURI());

		
        if(exception instanceof RequestParamInvalidJsonException){  
        	FieldError er =((RequestParamInvalidJsonException) exception).getFieldError();
            return mv.addObject("code", -101).addObject("error_msg", er.getField()+":"+er.getDefaultMessage()).addObject("error_type", "Param_Exception").addObject("Paramter", request.getParameterMap()); 
        }else if(exception instanceof DataReporterServiceException){  
        	return mv.addObject("code", -102).addObject("error_msg", exception.getMessage()).addObject("error_type", "Service_Exception"); 
        }  
		return mv.addObject("code",-103).addObject("error_msg", exception.getMessage()).addObject("error_type", "Unchek_Exception"); 
    }  
  
}  